package com.xpgk.mvc.dept;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.beetl.ext.fn.ParseInt;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantInit;
import com.xpgk.constant.ConstantRender;
import com.xpgk.dto.RenderBean;
import com.xpgk.dto.ZtreeNode;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.deptStation.DeptStation;
import com.xpgk.mvc.user.User;
import com.xpgk.mvc.user.UserService;
import com.xpgk.tools.ToolRandoms;

@Service(name = DepartmentService.serviceName)
public class DepartmentService extends BaseService {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(DepartmentService.class);

	public static final String serviceName = "departmentService";

	/**
	 * 部门树形图节点数据
	 * 
	 * @param cxt
	 * @param parentIds
	 * @return
	 */
	public List<ZtreeNode> childNodeData(String cxt, String parentIds, String curUserDeptids) {
		List<Department> list = null;
		if (null != parentIds) {
			String sql = getSqlMy(Department.sqlId_childNode);
			list = Department.dao.find(sql, parentIds);

		} else {
			list = new ArrayList<>();
			list.add(Department.dao.findById(curUserDeptids));
		}

		List<ZtreeNode> nodeList = new ArrayList<ZtreeNode>();
		ZtreeNode node = null;

		for (Department dept : list) {
			node = new ZtreeNode();
			node.setId(dept.getPKValue());
			node.setName(dept.getStr(Department.column_name));
			node.setBh(dept.getStr(Department.column_bh));
			node.setIsParent(dept.getStr(Department.column_isparent));
			node.setLevelNum(dept.getBigDecimal(Department.column_level).intValue());
			node.setIcon(cxt + ConstantRender.icon_path + dept.getStr(Department.column_icon));
			nodeList.add(node);
		}

		return nodeList;
	}

	/**
	 * 获取子节点列表数据
	 * 
	 * @param ids
	 * @return
	 */
	public List<Department> childrenDataList(String ids) {
		// Department dept = Department.dao.findById(ids);
		String sql = getSqlMy(Department.sqlId_childrenList);
		List<Department> depts = Department.dao.find(sql, ids);
		// depts.add(0, dept);
		return depts;
	}

	/**
	 * 保存
	 * 
	 * @param pIds
	 * @param names
	 * @param orderIds
	 * @return
	 */
	public String save(String pIds, String name, int orderId, int level, String pBh, String organIds) {
		Department pDept = Department.dao.findById(pIds);
		pDept.set(Department.column_isparent, "true").update();

		Department dept = new Department();
		dept.set(Department.column_isparent, "false");
		dept.set(Department.column_parentids, pIds);
		dept.set(Department.column_orderid, orderId);
		dept.set(Department.column_name, name);
		dept.set(Department.column_level, level + 1);
		dept.set(Department.column_bh, createBH(orderId, pBh, level + 1));
		dept.set(Department.column_organizationids, organIds);
		dept.save();

		return dept.getPKValue();
	}

	/**
	 * 更新
	 * 
	 * @param ids
	 * @param names
	 */
	public void update(String ids, String name) {
		Department dept = Department.dao.findById(ids);
		dept.set(Department.column_name, name).update();
	}

	/**
	 * 删除
	 * 
	 * @param ids
	 * @return
	 */
	public String delete(String ids) {
		Department department = Department.dao.findById(ids);

		// 是否存在子节点
		if (department.getStr(Department.column_isparent).equals("true")) {
			return "存在子部门，不能直接删除"; // 存在子节点，不能直接删除
		}

		// 部门下是否存在人
		String countSql = getSqlMy(Department.sqlId_userCount);
		long count = Db.use(ConstantInit.db_dataSource_main).queryNumber(countSql, ids).longValue();
		if (count != 0) {
			return "部门下存在人员，不能删除"; // 部门下存在人，不能删除
		}

		// 修改上级节点的isparent
		Department pDepartment = Department.dao.findById(department.getStr(Department.column_parentids));
		String sql = getSqlMy(Department.sqlId_childCount);
		Record record = Db.use(ConstantInit.db_dataSource_main).findFirst(sql, pDepartment.getPKValue());
		Long counts = record.getNumber("counts").longValue();
		if (counts == 1) {
			pDepartment.set(Department.column_isparent, "false");
			pDepartment.update();
		}

		// 删除
		Department.dao.deleteById(ids);

		return ConstantRender.render_success;
	}
	
	/**
	 * 设置权限tree
	 * @param cxt
	 * @param parentIds
	 * @param curUserStationids
	 * @return
	 */
	public List<ZtreeNode> stationChildNodeData(String cxt, String parentIds, String curUserStationids){
		List<DeptStation> list = null;
		if (null != parentIds) {
			String sql = getSqlMy(DeptStation.sqlId_childNode);
			list = DeptStation.dao.find(sql, parentIds);

		} else {
			list = new ArrayList<>();
			list.add(DeptStation.dao.findById(curUserStationids));
		}

		List<ZtreeNode> nodeList = new ArrayList<ZtreeNode>();
		ZtreeNode node = null;

		for (DeptStation station : list) {
			node = new ZtreeNode();
			node.setId(station.getPKValue());
			node.setName(station.getStr(DeptStation.column_name));
			node.setIsParent(station.getStr(DeptStation.column_isparent));
			node.setIcon(cxt + ConstantRender.icon_path + station.getStr(DeptStation.column_icon));
			nodeList.add(node);
		}

		return nodeList;
	}
	
	/**
	 * 添加用户
	 * @param user
	 * @param organIds
	 * @return
	 */
	public RenderBean addUser(User user, String organIds){
		RenderBean result = new RenderBean();
		User oldUser = User.cacheGetByUserName(user.getStr(User.column_username));
		if(null == oldUser){
			// 初始化用户
			String userIds = ToolRandoms.getUuid(true);
			user.set(User.column_organizationids, organIds);
			new UserService().save(userIds, user, "888888", null);
		
			result.setCode(ConstantRender.render_success_code);
		}else{
			result.setCode(ConstantRender.render_error_code);
			result.setMsg("该用户名已经被其他人占用，请修改后重试!");
		}
		return result;
	}
	
	/**
	 * 修改用户
	 * @param user
	 * @param organIds
	 * @return
	 */
	public RenderBean upUser(User user){
		RenderBean result = new RenderBean();
		User oldUser = User.cacheGetByUserName(user.getStr(User.column_username));
		if(null == oldUser){
			new UserService().update(user, null, null);
			result.setCode(ConstantRender.render_success_code);
		}else{
			if(user.getPKValue().equals(oldUser.getPKValue())){
				new UserService().update(user, null, null);
				result.setCode(ConstantRender.render_success_code);
			}else{
				result.setCode(ConstantRender.render_error_code);
				result.setMsg("该用户名已经被其他人占用，请修改后重试!");
			}
			
		}
		return result;
	}

}
